package com.net.oil.oilWear;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.android.material.tabs.TabLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.net.oil.R;
import com.net.oil.base.BaseActivity;
import com.net.oil.car.bean.CarBean;
import com.net.oil.oilWear.bean.OilWearChartBean;
import com.net.oil.oilWear.bean.OilWearInfo;
import com.net.oil.oilWear.contract.OilWearContract;
import com.net.oil.oilWear.presenter.OilWearPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OilWearActivity extends BaseActivity<OilWearPresenter> implements OilWearContract.View {

    public static final String INTENT_CAR_LIST_KEY = "intent_car_list_key";     //进入该页面传入的车辆信息的key
    private static final int AddOilRequestCode = 11;        //进入添加记录界面的requestCode
    private static final int OilRecordRequestCode = 12;     //进入加油记录列表页面的requestCode

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_add)
    ImageView toolbarAdd;
    @BindView(R.id.oil_wear_value_tv)
    TextView oilWearValueTv;
    @BindView(R.id.oil_wear_count_tv)
    TextView oilWearCountTv;
    @BindView(R.id.avg_mileage_day_tv)
    TextView avgMileageDayTv;
    @BindView(R.id.fill_oil_cycle_tv)
    TextView fillOilCycleTv;
    @BindView(R.id.mileage_count_tv)
    TextView mileageCountTv;
    @BindView(R.id.fill_oil_count_tv)
    TextView fillOilCountTv;
    @BindView(R.id.avg_oil_money_tv)
    TextView avgOilMoneyTv;
    @BindView(R.id.chart)
    LineChart chart;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.fill_oil_record_tv)
    TextView fillOilRecordTv;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.no_date_layout)
    LinearLayout noDateLayout;

    private ArrayList<CarBean> carBeans;

    private int currentCarId = -1;

    private XAxis xAxis;                //X轴
    private YAxis leftYAxis;            //左侧Y轴
    private YAxis rightYaxis;           //右侧Y轴
    private Legend legend;              //图例

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_oil_wear);
        ButterKnife.bind(this);
        presenter = new OilWearPresenter(this);
        initData();
        initView();
        initChart();
    }

    private void initData() {
        try {
            String carBeanJson = getIntent().getStringExtra(INTENT_CAR_LIST_KEY);
            Gson gson = new Gson();
            carBeans = gson.fromJson(carBeanJson, new TypeToken<List<CarBean>>() {
            }.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        toolbarTitle.setText("油耗计算");

        if (carBeans != null && carBeans.size() > 0){
            /* 初始化spinner */
            String[] carNames = new String[carBeans.size()];
            for (int i = 0; i < carBeans.size(); i++) {
                if (carBeans.get(i).getCarModelInfo() != null) {
                    String carName = carBeans.get(i).getCarModelInfo().getBrand();
                    if (!TextUtils.isEmpty(carName)) {
                        /* spinner内容 */
                        carNames[i] = carBeans.get(i).getCarModelInfo().getBrand();
                    }
                }

            }
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
                    R.layout.spinner_layout, carNames);
            spinnerAdapter.setDropDownViewResource(R.layout.spinner_drop_layout);
            spinner.setAdapter(spinnerAdapter);
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    currentCarId = carBeans.get(position).getId();
                    initDataFormServer();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        }

        /* 初始化tabLayout */
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tabLayoutItemSwitch(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    /**
     * 从服务器端获取数据
     */
    private void initDataFormServer(){
        if (currentCarId != -1) {
            presenter.getOilWearInfo(currentCarId);
            presenter.getOilWearChartData(currentCarId, 3);
            tabLayout.getTabAt(0).select();
        }
    }


    /**
     * 根据tabLayout选中的位置，获取对应的数据
     * 注：条件 3:3个月 6:半年 12：一年
     *
     * @param position tabLayout item选中的位置
     */
    private void tabLayoutItemSwitch(int position) {
        /* 对应位置0 3个月，1 半年， 2 一年， 3 全部 */
        switch (position) {
            case 0:
                presenter.getOilWearChartData(currentCarId, 3);
                break;
            case 1:
                presenter.getOilWearChartData(currentCarId, 6);
                break;
            case 2:
                presenter.getOilWearChartData(currentCarId, 12);
                break;
        }
    }

    /**
     * 更新view
     *
     * @param oilWearInfo 油耗信息
     */
    private void updateView(OilWearInfo oilWearInfo) {
        /* 累计油耗 */
        oilWearCountTv.setText(String.valueOf(oilWearInfo.getAverageFuelConsumption()));
        /* 平均行驶 */
        avgMileageDayTv.setText(String.valueOf(oilWearInfo.getAverageDailyMileage()));
        /* 加油周期 */
        fillOilCycleTv.setText(String.valueOf(oilWearInfo.getCycle()));
        /* 累计里程 */
        mileageCountTv.setText(String.valueOf(oilWearInfo.getCurrentMileage()));
        /* 累计加油 */
        fillOilCountTv.setText(String.valueOf(oilWearInfo.getTotalRefueling()));
        /* 平均油费 */
        avgOilMoneyTv.setText(String.valueOf(oilWearInfo.getAverageMonthlyMoney()));

        /* 最新油耗 */
        oilWearValueTv.setText(String.valueOf(oilWearInfo.getAverageFuelConsumption()));
    }

    /**
     * 获取加油详情数据成功
     *
     * @param oilWearInfo 加油详情数据
     */
    @Override
    public void getOilWearInfoSuccess(OilWearInfo oilWearInfo) {
        if (oilWearInfo != null) {
            updateView(oilWearInfo);
        }
    }

    /**
     * 获取加油详情数据失败
     */
    @Override
    public void getOilWearInfoFailed() {

    }

    /**
     * 获取折线图数据成功
     *
     * @param oilWearChartBeans 数据
     */
    @Override
    public void getOilWearChartDataSuccess(final List<OilWearChartBean> oilWearChartBeans) {
        chart.clear();
        List<Entry> entries = new ArrayList<>();
        if (oilWearChartBeans != null && oilWearChartBeans.size() > 0) {
            chart.setVisibility(View.VISIBLE);
            noDateLayout.setVisibility(View.GONE);
            for (int i = 0; i < oilWearChartBeans.size(); i++) {
                Entry entry = new Entry(i, (float) oilWearChartBeans.get(i).getOilAvg());
                entries.add(entry);
            }

            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    int index  = (int) value;
                    if (index < 0 || index >= oilWearChartBeans.size()){
                        return "";
                    }else {
                        return oilWearChartBeans.get(index).getDate();
                    }
                }
            });
            LineDataSet lineDataSet = new LineDataSet(entries, "");
            initLineDataSet(lineDataSet);
            LineData lineData = new LineData(lineDataSet);
            chart.setData(lineData);
            chart.invalidate();
        }else {
            chart.setVisibility(View.GONE);
            noDateLayout.setVisibility(View.VISIBLE);
        }


    }

    /**
     * 获取折线图数据失败
     */
    @Override
    public void getOilWearChartDataFailed() {
        if (chart != null) {
            chart.clear();
            chart.setVisibility(View.GONE);
            noDateLayout.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.toolbar_go_back, R.id.toolbar_add, R.id.fill_oil_record_tv})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.toolbar_go_back:
                finish();
                break;
            case R.id.toolbar_add:
                intent = new Intent(this, AddOilWearActivity.class);
                intent.putExtra(AddOilWearActivity.IntentCarId, currentCarId);
                startActivityForResult(intent, AddOilRequestCode);
                break;
            case R.id.fill_oil_record_tv:
                intent = new Intent(this, FillOilRecordActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(AddOilWearActivity.IntentType, AddOilWearActivity.EDIT);
                bundle.putInt(FillOilRecordActivity.IntentCarId, currentCarId);
                intent.putExtras(bundle);
                startActivityForResult(intent, OilRecordRequestCode);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == AddOilRequestCode || requestCode == OilRecordRequestCode){
                initDataFormServer();
            }
        }
    }

    /**
     * 初始化图表
     */
    private void initChart() {
        /* 图表设置 */
        //是否展示网格线
        chart.setDrawGridBackground(false);
        //是否显示边界
        chart.setDrawBorders(false);
        //是否可以拖动
        chart.setDragEnabled(false);
        //是否有触摸事件
        chart.setTouchEnabled(false);
        Description description = new Description();
        description.setText("");
        chart.setDescription(description);

        /* XY轴的设置 */
        xAxis = chart.getXAxis();
        xAxis.setDrawGridLines(false);
        leftYAxis = chart.getAxisLeft();
        rightYaxis = chart.getAxisRight();
        rightYaxis.setEnabled(false);
        leftYAxis.setDrawGridLines(true);
        leftYAxis.setGranularity(1f);

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        xAxis.setAvoidFirstLastClipping(true);
        /*  折线图例 标签 设置  */
        legend = chart.getLegend();
        legend.setEnabled(false);

    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     */
    private void initLineDataSet(LineDataSet lineDataSet) {
        lineDataSet.setColor(Color.BLUE);
        lineDataSet.setCircleColor(Color.BLUE);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
    }

}
